package com.niit.project.service.impl;

import com.niit.project.dao.BadGoodsDao;
import com.niit.project.dao.impl.BadGoodsDaoImpl;
import com.niit.project.entity.BadGoods;
import com.niit.project.entity.Page;
import com.niit.project.service.BadGoodsService;
import com.niit.project.utils.Dbutils;

import java.util.List;

public class BadGoodsServiceImpl implements BadGoodsService {
    //创建一个实例化对象，方便后续引用dao层中的方法
    BadGoodsDao badGoodsDao = new BadGoodsDaoImpl();
    //分页展示
    @Override
    public List<BadGoods> showAllByPage(Page page) {
        List<BadGoods> badGoods = null;
        try {
            //事务开启，可以不了解，这是我后期加上的
            Dbutils.begin();
            //获取总商品数
            long count = badGoodsDao.selectCount();
            //设置页码总数
            page.setTotalCounts((int) count);
            //选取限定范围内的总商品
            badGoods = badGoodsDao.selectAll(page);
            //事务的提交
            Dbutils.commit();
        } catch (Exception e) {
            //出现异常时事务的回滚
            Dbutils.rollback();
            throw new RuntimeException(e);
        }
        return badGoods;
    }

    @Override
    public int deleteGoods(int id) {
        int result = 0;
        try {
            Dbutils.begin();
            result = badGoodsDao.delete(id);
            Dbutils.commit();
        } catch (Exception e) {
            Dbutils.rollback();
            throw new RuntimeException(e);
        }
        return result;
    }

    @Override
    public BadGoods selectBadGoodsById(int id) {
        BadGoods badGoods = null;
        try {
            Dbutils.begin();
            badGoods = badGoodsDao.select(id);
            Dbutils.commit();
        } catch (Exception e) {
            Dbutils.rollback();
            throw new RuntimeException(e);
        }
        return badGoods;
    }

    @Override
    public int addGoods(BadGoods badGoods) {
        int result = 0;
        try {
            Dbutils.begin();
            result = badGoodsDao.insert(badGoods);
            Dbutils.commit();
        } catch (Exception e) {
            Dbutils.rollback();
            throw new RuntimeException(e);
        }
        return result;
    }
}
